package org.example.aop;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.mapper.OperateLogMapper;
import org.example.pojo.OperateLog;
import org.example.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 包名：org.example.aop
 * 用户：admin
 * 日期：2025-09-16
 * 项目名称：pro-demo
 */
@Slf4j
@Component
@Aspect
public class LogAspect {

    @Autowired(required = false)
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(org.example.anno.Log)")
    public Object recording(ProceedingJoinPoint joinPoint) throws Throwable{
        //获取访问对象id，得到对象map
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);

        //得到对象参数
        Integer operateUser = (Integer)claims.get("id");
        LocalDateTime operateTime = LocalDateTime.now();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);
        long beginTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        String returnValue = JSONObject.toJSONString(result);
        Long costTime = endTime - beginTime;

        //插入log记录
        OperateLog po = new OperateLog(null,operateUser,operateTime,className,methodName,methodParams,returnValue,costTime);
        log.info("AOP操作日志：{}",po);
        operateLogMapper.insert(po);
        return result;

    }
}
